package com.study.spring.udp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Arrays;

public class UdpServer implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(UdpServer.class);
    private static final int PORT = 9991;
    private static final int MAX_LEN = 1024;
    private DatagramSocket datagramSocket;

    public static void main(String[] args) {
        new Thread(new UdpServer()).start();
    }

    private void init() {
        try {
            datagramSocket = new DatagramSocket(PORT);
            LOGGER.info("upd 服务启动成功!");
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    private void receive(DatagramPacket packet) throws IOException {
        datagramSocket.receive(packet);
    }

    private void response(DatagramPacket packet) throws IOException {
        datagramSocket.send(packet);
    }

    @Override
    public void run() {
        init();
        while (true) {
            try {
                byte[] buffer = new byte[MAX_LEN];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                receive(packet);
                byte[] body = packet.getData();
                int head1 = body[0];
                byte head2 = body[1];
                String receStr = new String(packet.getData(), 0, packet.getLength());
                LOGGER.info("接收到的数据包=" + receStr);
                byte[] bt = new byte[packet.getLength()];

                System.arraycopy(packet.getData(), 0, bt, 0, packet.getLength());
                LOGGER.info(packet.getAddress().getHostAddress() + "：" + packet.getPort() + "：" + Arrays.toString(bt));
                packet.setData(bt);
                response(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
